<template>
  <div class="order-container">
    <!-- 左侧购物车列表 -->
    <div class="cart-section">
      <h2 class="section-title">购物车</h2>
      <div class="cart-items" v-if="cartItems.length > 0">
        <div class="cart-item" v-for="item in cartItems" :key="item.productId">
          <img
            :src="`http://127.0.0.1:8000${item.image}`"
            :alt="item.name"
            class="item-image"
          />
          <div class="item-details">
            <h3 class="item-name">{{ item.name }}</h3>
            <p class="item-price">¥{{ item.price }}</p>
            <div class="item-quantity">
              <span>数量: {{ item.quantity }}</span>
            </div>
          </div>
          <div class="item-total">
            ¥{{ item.price * item.quantity }}
            <el-button
              type="danger"
              :icon="Delete"
              circle
              size="small"
              class="delete-btn"
              @click="removeFromCart(item.productId)"
            />
          </div>
        </div>
        <div class="cart-summary">
          <div class="summary-item">
            <span>小计:</span>
            <span>¥{{ cartTotal }}</span>
          </div>
          <div class="summary-item total">
            <span>总计:</span>
            <span>¥{{ cartTotal }}</span>
          </div>
          <el-button type="primary" class="checkout-btn" @click="handleCheckout"
            >结算</el-button
          >
        </div>
      </div>
      <div class="empty-cart" v-else>
        <p>购物车为空</p>
      </div>
    </div>

    <!-- 右侧订单列表 -->
    <div class="orders-section">
      <h2 class="section-title">我的订单</h2>
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="id" label="订单号" width="180" />
        <el-table-column prop="date" label="日期" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <span :class="getStatusClass(row.status)">{{
              getStatusText(row.status)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="总价" width="100" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <div class="order-actions">
              <el-button
                v-if="row.status === 'pending'"
                size="small"
                type="primary"
                @click="payOrder(row.id)"
              >
                去支付
              </el-button>
              <el-button size="small" @click="viewOrderDetail(row.id)">
                查看详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="cancelOrder(row.id)"
                v-if="row.status !== 'shipped'"
              >
                取消订单
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="dialogVisible" title="订单详情" width="50%" center>
      <div v-if="currentOrderDetail">
        <div class="order-info">
          <p><strong>订单号:</strong> {{ currentOrderDetail.order_number }}</p>
          <p>
            <strong>下单时间:</strong>
            {{ new Date(currentOrderDetail.order_time).toLocaleString() }}
          </p>
          <p>
            <strong>订单状态:</strong>
            <span :class="getStatusClass(currentOrderDetail.status)">{{
              getStatusText(currentOrderDetail.status)
            }}</span>
          </p>
          <p>
            <strong>总金额:</strong> ¥{{
              parseFloat(currentOrderDetail.total_price).toFixed(2)
            }}
          </p>
        </div>

        <div class="order-items">
          <h3>商品列表</h3>
          <div class="item-list">
            <div
              v-for="item in currentOrderDetail.items"
              :key="item.product"
              class="order-item"
            >
              <img
                :src="`http://127.0.0.1:8000${item.product_image}`"
                alt="{{ item.product_name }}"
                class="item-image"
              />
              <div class="item-info">
                <p class="item-name">{{ item.product_name }}</p>
                <p class="item-price">¥{{ item.product_price }}</p>
                <p class="item-quantity">数量: {{ item.quantity }}</p>
              </div>
              <div class="item-total">
                ¥{{ (item.product_price * item.quantity).toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useStore } from "vuex";
import { ElMessage, ElDialog, ElMessageBox } from "element-plus";
import axiosInstance from "../../utils/requests.js";
import { Delete } from "@element-plus/icons-vue";

const store = useStore();

// 从Vuex store获取购物车列表
const cartItems = computed(() => {
  return store.getters["mall/cartList"];
});

// 订单列表数据（初始为空数组）
const orders = ref([]);
// 计算购物车总价
const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
});

// 添加订单详情弹窗相关变量
const dialogVisible = ref(false);
const currentOrderDetail = ref(null);

// 获取订单状态对应的样式
const getStatusClass = (status) => {
  switch (status) {
    case "completed":
      return "status-completed";
    case "shipped":
      return "status-shipped";
    case "cancelled":
      return "status-cancelled";
    case "paid":
      return "status-paid";
    default:
      return "status-pending";
  }
};

// 获取订单状态的中文显示
const getStatusText = (status) => {
  const statusMap = {
    pending: "待支付",
    paid: "已支付",
    shipped: "已发货",
    completed: "已完成",
    cancelled: "已取消",
  };
  return statusMap[status] || status;
};

// 查看订单详情
const viewOrderDetail = (orderId) => {
  // 查找对应的订单
  const order = orders.value.find((o) => o.id === orderId);
  if (order) {
    currentOrderDetail.value = order.originalData;
    dialogVisible.value = true;
  } else {
    ElMessage.error("未找到该订单信息");
  }
};

// 获取用户的订单列表
const fetchUserOrders = async () => {
  try {
    const response = await axiosInstance.get("/api/order/orders/");
    // 格式化订单数据以匹配前端显示需求
    const formattedOrders = response.data.map((order) => ({
      id: order.order_number,
      date: new Date(order.order_time).toISOString().split("T")[0],
      status: order.status,
      // 修改：确保total_price是数字类型后再调用toFixed
      total: `¥${parseFloat(order.total_price).toFixed(2)}`,
      originalData: order, // 保存原始数据，方便后续操作
    }));
    orders.value = formattedOrders;
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败，请稍后重试");
  }
};

// 从购物车移除商品
const removeFromCart = (productId) => {
  store.dispatch("mall/removeFromCart", productId);
  ElMessage.success("已从购物车移除商品");
};

// 处理结算功能
const handleCheckout = async () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning("购物车为空，无法结算");
    return;
  }

  // 构建订单数据
  const orderItems = cartItems.value.map((item) => ({
    product_id: item.productId,
    quantity: item.quantity,
    price: item.price,
  }));

  try {
    // 发送创建订单请求
    const response = await axiosInstance.post("/api/order/orders/", {
      order_items: orderItems,
      total_price: cartTotal.value,
    });

    // 处理订单创建成功
    ElMessage.success("订单创建成功！");

    // 重新获取订单列表，确保显示最新订单
    await fetchUserOrders();

    // 清空购物车
    store.commit("mall/SET_CART_LIST", []);
  } catch (error) {
    console.error("创建订单失败:", error);
    const errorMsg =
      error.response?.data?.error ||
      error.message ||
      "创建订单失败，请稍后重试";
    ElMessage.error(errorMsg);
  }
};

//取消订单按钮
const cancelOrder = async (orderId) => {
  try {
    // 查找订单获取其原始ID
    const order = orders.value.find((o) => o.id === orderId);
    if (!order) {
      ElMessage.error("未找到该订单");
      return;
    }

    // 显示确认对话框
    const confirmResult = await ElMessageBox.confirm(
      "确定要删除此订单吗？此操作不可撤销。",
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 用户确认删除后执行操作
    if (confirmResult === "confirm") {
      // 使用正确的ID调用DELETE API
      await axiosInstance.delete(`/api/order/orders/${order.originalData.id}/`);

      ElMessage.success("订单已成功删除");
      // 重新获取订单列表，更新UI
      await fetchUserOrders();
    }
  } catch (error) {
    // 如果是用户取消操作，不显示错误信息
    if (error === "cancel") {
      return;
    }

    console.error("删除订单失败:", error);

    // 即使后端请求失败，我们也尝试在前端更新列表
    const orderIndex = orders.value.findIndex((o) => o.id === orderId);
    if (orderIndex !== -1) {
      orders.value.splice(orderIndex, 1);
      orders.value = [...orders.value]; // 触发响应式更新
      ElMessage.warning("已在本地移除订单");
    } else {
      ElMessage.error("删除订单失败，请稍后重试");
    }
  }
};

// 支付订单按钮
const payOrder = async (orderId) => {
  try {
    // 查找订单
    const order = orders.value.find((o) => o.id === orderId);

    if (!order) {
      ElMessage.error("未找到该订单");
      return;
    }

    // 修复：使用正确的原始ID
    await axiosInstance.post(
      `/api/order/orders/${order.originalData.id}/change_status/`,
      {
        status: "paid",
      },
      {
        withCredentials: true, // 确保带上认证信息
      }
    );

    // 显示支付成功提示
    ElMessage.success("支付成功！");

    // 重新获取订单列表，更新UI
    await fetchUserOrders();
  } catch (error) {
    console.error("支付失败:", error);
    const errorMsg =
      error.response?.data?.error || error.message || "支付失败，请稍后重试";
    ElMessage.error(errorMsg);
  }
};
// 组件挂载时获取订单列表
onMounted(() => {
  fetchUserOrders();
});
</script>
<style lang="less" scoped>
.order-container {
  display: flex;
  min-height: 100vh;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.cart-section {
  width: 30%;
  min-width: 30%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-right: 10px;
  flex-shrink: 0;
}

.orders-section {
  width: 60%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.cart-items {
  .cart-item {
    display: flex;
    padding: 15px 0;
    border-bottom: 1px solid #eee;
    &:last-child {
      border-bottom: none;
    }

    .item-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 15px;
    }

    .item-details {
      flex: 1;
      .item-name {
        font-size: 16px;
        margin-bottom: 5px;
        color: #333;
      }

      .item-price {
        font-size: 14px;
        color: #8d26e6;
        font-weight: 500;
        margin-bottom: 5px;
      }

      .item-quantity {
        font-size: 14px;
        color: #666;
      }
    }
    .item-total {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      min-width: 60px;
      position: relative;
      display: flex;
      align-items: center;
    }
    .delete-btn {
      position: absolute;
      right: -10px;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .cart-summary {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;

    .summary-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      font-size: 14px;

      &.total {
        font-size: 16px;
        font-weight: 600;
        margin-top: 15px;
      }
    }

    .checkout-btn {
      width: 100%;
      margin-top: 20px;
      background-color: #8d26e6;
      border-color: #8d26e6;
      &:hover {
        background-color: #a259ff;
        border-color: #a259ff;
      }
    }
  }
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

// 订单状态样式
.status-completed {
  color: #26e68d;
}

.status-shipped {
  color: #2686e6;
}

.status-cancelled {
  color: #e62626;
}

.status-pending {
  color: #e6b426;
}

// 响应式调整
@media (max-width: 992px) {
  .order-container {
    flex-direction: column;
  }

  .cart-section,
  .orders-section {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }
}

.order-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  p {
    margin-bottom: 8px;
  }
}

.order-items {
  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #333;
  }
}

.item-list {
  .order-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    &:last-child {
      border-bottom: none;
    }
    .item-image {
      width: 60px;
      height: 60px;
      object-fit: cover;
      border-radius: 4px;
      margin-right: 15px;
    }
    .item-info {
      flex: 1;
      .item-name {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
      }
      .item-price {
        font-size: 14px;
        color: #8d26e6;
        margin-bottom: 5px;
      }
      .item-quantity {
        font-size: 12px;
        color: #666;
      }
    }
    .item-total {
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
  }
}
.order-actions {
  display: flex;
}
</style>
